package com.whale.nangua.pumpkingobang.aty;

import static com.whale.nangua.pumpkingobang.aty.InitAty.server_flag;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.example.wuziqi.R;
import com.whale.nangua.pumpkingobang.Network.TCP_Network;
import com.whale.nangua.pumpkingobang.adapter.ReplayAdapter;
import com.whale.nangua.pumpkingobang.bean.ReplayData;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class FupanSelectAty extends AppCompatActivity {

    // ListView和数据源
    private ListView replayListView;
    private List<ReplayData> replayDataList;
    private ReplayAdapter adapter;
    private TCP_Network client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fupan_select);

        replayListView = findViewById(R.id.fupang_select);
        replayDataList = new ArrayList<>();
        client = (TCP_Network) this.getApplication();
        // 从数据库获取复盘数据及对应的落子信息
        getReplayShow();
        adapter = new ReplayAdapter(this, replayDataList);
        replayListView.setAdapter(adapter);



        replayListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ReplayData selectedReplay = replayDataList.get(position);
                selectedReplay.addMoveInfo(getReplay(replayDataList.get(position).getGameId()));
                Intent intent = new Intent(FupanSelectAty.this, FuPanAty.class);
                Bundle data = new Bundle();
                data.putSerializable("replay", selectedReplay);
                intent.putExtras(data);
                startActivity(intent);
            }
        });
    }

    // 获取复盘列表展示数据
    private void getReplayShow() {
        if (!server_flag) {
            final androidx.appcompat.app.AlertDialog.Builder alterDiaglog = new androidx.appcompat.app.AlertDialog.Builder(this);
            alterDiaglog.setTitle("服务器连接失败");
            alterDiaglog.setMessage("请先登录");
            alterDiaglog.setPositiveButton("确定", null);
            alterDiaglog.show();
            return;
        }

        String game_id = "";
        JSONObject requestObject = new JSONObject();
        try {
            requestObject.put("function", "replayShow");
            requestObject.put("game_id", game_id);

            String responseStr = client.sendAndReceiveMessage(requestObject.toString());
            if (responseStr!= null &&!responseStr.isEmpty()) {
                JSONObject responseObject = JSONObject.parseObject(responseStr);
                if (responseObject.containsKey("function") && "replayShow".equals(responseObject.getString("function"))) {
                    if (responseObject.containsKey("replays")) {
                        JSONArray replaysArray = responseObject.getJSONArray("replays");
                        for (int i = 0; i < replaysArray.size(); i++) {
                            JSONObject replayObj = replaysArray.getJSONObject(i);
                            String gameId = replayObj.getString("game_id");
                            String endTime = replayObj.getString("end_time");
                            ReplayData replayData = new ReplayData(gameId,endTime);
                            replayDataList.add(replayData);
                        }
                    } else {
                        System.err.println("服务器响应的 'replayShow' 数据中缺少'replays' 字段");
                    }
                } else {
                    System.err.println("服务器响应的消息不符合 'replayShow' 功能预期");
                }
            } else {
                System.err.println("接收到的服务器响应消息为空");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            System.err.println("解析服务器响应消息时出现 JSON 解析错误");
        }
    }

    // 获取具体复盘数据（落子信息）
    private List<ReplayData.MoveInfo> getReplay(String game_id) {
        JSONObject requestObject = new JSONObject();
        List<ReplayData.MoveInfo> moveInfoList = new ArrayList<>();
        try {
            requestObject.put("function", "replay");
            requestObject.put("game_id", game_id);

            String responseStr = client.sendAndReceiveMessage(requestObject.toString());
            if (responseStr!= null &&!responseStr.isEmpty()) {
                JSONObject responseObject = JSONObject.parseObject(responseStr);
                if (responseObject.containsKey("function") && "replay".equals(responseObject.getString("function"))) {
                    if (responseObject.containsKey("moves")) {
                        JSONArray movesArray = responseObject.getJSONArray("moves");
                        for (int i = 0; i < movesArray.size(); i++) {
                            JSONObject moveObj = movesArray.getJSONObject(i);
                            int x = moveObj.getInteger("x_coordinate");
                            int y = moveObj.getInteger("y_coordinate");
                            int playerColor = moveObj.getInteger("player_color");
                            int moveOrder = moveObj.getInteger("move_order");
                            ReplayData.MoveInfo moveInfo = new ReplayData.MoveInfo(x,y,playerColor,moveOrder);
                            moveInfoList.add(moveInfo);
                        }
                    } else {
                        System.err.println("服务器响应的'replay' 数据中缺少'moves' 字段");
                    }
                } else {
                    System.err.println("服务器响应的消息不符合'replay' 功能预期");
                }
            } else {
                System.err.println("接收到的服务器响应消息为空");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            System.err.println("解析服务器响应消息时出现 JSON 解析错误");
        }
        return moveInfoList;
    }

}

